<?php
/**
 * Created by PhpStorm.
 * User: zyh
 * Date: 2018/5/4
 * Time: 上午9:08
 */

namespace app\index\command;

use app\admin\model\Game;
use app\admin\model\Rewards;
use app\admin\model\User;
use GatewayClient\Gateway;
use think\Cache;
use think\console\Input;
use think\console\Output;
use think\Session;

class Events
{

    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id) {

        $init_msg = '{"type":"init","data":"'.$client_id.'"}';
        //假如管理员出现故障 再次进入 需要重新发送game_update数据
        Gateway::sendToClient($client_id,$init_msg);

    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message) {
        $game = new Game();
        $output = new Output();
        $output->writeln("--------------------------------------------------------");
        $output->writeln($message);
        $output->writeln("--------------------------------------------------------");

        $msg = json_decode($message,true);
        switch ($msg['type']){
            //管理端数据变更
            case "game_change":
                $rewards = new Rewards();
                $status = Game::get($msg['id'])['status'];//变更前的阶段
                if ($msg['status']>0){
                    $id = $game->save(['status'=>$msg['status']],['id'=>$msg['id']]);

                    if ($id) {
                        //结算上一阶段信息 返回放扣方
                        $kou = $rewards->settlement($msg['id'],$status);
                        //放扣身份 1 红方大  本回合开始红方放扣 2 蓝方大 本回合开始蓝方放扣
                        if ($msg['status'] ==10 || $msg['status'] <= 0){
                            Cache::set("kou",0);
                        }else{
                            Cache::set("kou",$kou);
                        }
                        $data = self::getReportContent($msg['id']);
                        Gateway::sendToAll(json_encode($data));
                        Events::report($client_id,true);
                    }else{
                        Events::report($client_id,false);
                    }
                }else{
                    //-1  请求结算本局
                    $kou = $rewards->settlement($msg['id'],$status,$msg['data']['winner']);
                    if ($kou == -1){
                        Game::get($msg['id'])->save(['status'=>-1]);
                        $result['type'] = "result";
                        Gateway::sendToUid('admin',json_encode($result));
                        Gateway::sendToGroup('user',json_encode($result));
                    }
                }
                break;
            //请求最近比赛数据
            case "report":
                $data = self::getReportContent($msg['id']);
                $output->writeln("info:".json_encode($data));
                Gateway::sendToClient($client_id,json_encode($data));
                break;
                //客户端提交投注
            case "reward":
                $score = $msg['score'];
                //检查用户余额
                if (User::get($msg['uid'])['score']<$msg['score']){
                    self::report($client_id,false,"余额不足");
                }
                //前端和后端字段不一致 在这里调整
                $data['uid'] = $msg['uid'];
                $data['kid'] = $msg['status'];
                $data['gid'] = $msg['no'];
                $data['reward'] = $score;
                $data['direction'] = $msg['who'];
                $data['create_time'] = time();
                //当前放扣身份
                $data['kou'] = Cache::get('kou');
                $rewards = new Rewards();
                $in = $rewards->insertReward($data);
                if ($in){
                    self::report($client_id,true);
                    //通知用户刷新余额
                    $s['type'] = "score_update";
                    $s['data'] = User::get($data['uid'])['score'];
                    //让客户端刷新余额
                    Gateway::sendToClient($client_id,json_encode($s));
                    $m = self::getReportContent($data['gid']);
                    Gateway::sendToAll(json_encode($m));
                }else{
                    self::report($client_id,false,"余额不足");
                }
                break;
            //客户端通知发送结算信息
            case "result":
                $out = new Output();
                $out->writeln("客户端请求结算信息");
                $out->writeln(print_r($msg,true));
                break;
            //聊天信息
            case "chat":
                $data['type'] = "chat";
                if ($msg['content']=='login'){
                    $data['from'] = "system";
                    $data['content'] = Session::get("user")['id']."进入房间";
                }else{
                    $data['from'] = Session::get("user")['id'];
                    $data['content'] = $msg['content'];
                }
                Gateway::sendToAll(json_encode($data));
                break;
        }
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id) {

    }

    //组装游戏返回信息
    public static function getReportContent($id)
    {
        $game = new Game();
        $rewards = new Rewards();
        //查询所有表信息  返回
        $info = $rewards->getRewardsInfo($id);
        $m['data'] = $info;
        $m['type'] = "game_update";
        return $m;
    }

    //组装返回结果
    public static function report($client_id,$status,$msg="")
    {
        $arr = ["type"=>"status","data"=>$status,"msg"=>$msg];
        Gateway::sendToClient($client_id,json_encode($arr));
    }

}